#!/usr/bin/python3
# -*- encoding: utf-8 -*-
'''
@文件    :   watchYOLOimages.py
@时间    :   2025/08/30 12:48:06
@作者  :   Thinktank
@版本 :   1.0
@简介 :   
@许可 :   
@描述    :   None
'''

# 这里放 import lib
import time
import os
import sys
# 添加当前目录到Python路径中
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from threading import Thread
# 修改导入方式，使用相对导入或者绝对导入
# 如果myyolo是同级目录下的模块
from myyolo import watchYOLOimages, watchSingleYOLOimage, yolo_init

TARGETFILENAMES = ['清污机2']
# folder_path = r"D:\myGitee\control-net\data\onecloud\temp_2.jpg"  # 根据实际情况修改文件夹路径
folder_path = r"D:\myGitee\control-net\filedata"  # 根据实际情况修改文件夹路径
output_folder = r"D:\results"  # 结果保存文件夹
model_path = r"./models/best_0903_640.pt"  # 根据实际情况修改模型路径
print("主要参数如下")
print("监视文件名：", TARGETFILENAMES)
print("监视文件夹：", folder_path)
print("输出文件夹", output_folder)
print("模型文件：", model_path)


class FolderWatcher(FileSystemEventHandler):
    def __init__(self, folder_path):
        self.folder_path = folder_path
        self.yolo = yolo_init(model_path)

    def on_created(self, event):
        if not event.is_directory:
            print(f"文件创建: {event.src_path}")
            if self.yolo:
                for filename in TARGETFILENAMES:
                    if filename in event.src_path:
                        print(f"检测到目标文件 {filename} 的创建，开始处理...")
                        time.sleep(2)
                        th = Thread(target=watchSingleYOLOimage,
                                    args=(self.yolo, event.src_path,
                                          output_folder, 0.15, 0.45))
                        th.start()

                    # watchYOLOimages(model_path,folder_path,output_folder,0.15,0.45)
    def on_deleted(self, event):
        if not event.is_directory:
            print(f"文件删除: {event.src_path}")

    def on_modified(self, event):
        if not event.is_directory:
            print(f"文件修改: {event.src_path}")

    def on_moved(self, event):
        if not event.is_directory:
            print(f"文件移动: {event.src_path} -> {event.dest_path}")


def monitor_folder(folder_path):
    if not os.path.exists(folder_path):
        print(f"文件夹不存在: {folder_path}")
        return

    event_handler = FolderWatcher(folder_path)
    observer = Observer()
    observer.schedule(event_handler, folder_path, recursive=True)

    observer.start()
    print(f"开始监控文件夹: {folder_path}")

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        print("监控已停止")

    observer.join()


if __name__ == "__main__":
    # 设置要监控的文件夹路径
    monitor_folder(folder_path)
